//
//  JShareTool.m
//  JW_BasePorject
//
//  Created by JW on 2018/5/2.
//  Copyright © 2018年 JW. All rights reserved.
//

#import "JShareTool.h"
//#import "JSHAREService.h"
//#import "ShareView.h"
#import "JShareConst.h"

@interface JShareTool ()

@property (nonatomic, strong) ShareView *shareView;
@property (nonatomic, strong) JSHAREMessage *shareMsg;


@end

@implementation JShareTool



/**
 配置分享参数
 */
+ (void)setupJShareConfig{
    JSHARELaunchConfig *config = [[JSHARELaunchConfig alloc] init];
    
    config.appKey = JShareAppKey;
    
    config.WeChatAppId = JShareWXAppID;
    config.WeChatAppSecret = JShareWXAppSecret;
    
    config.QQAppId = JShareQQAppID;
    config.QQAppKey = JShareQQAppKey;
    
    [JSHAREService setupWithConfig:config];
    [JSHAREService setDebug:YES];
    
}

+ (void)shareViewAddSuperview:(UIView *)view withMessage:(JSHAREMessage *)message{
    JShareTool *shareTool = [[JShareTool alloc] init];
    shareTool.shareMsg = message;
    
    [shareTool.shareView showWithContentType:JSHARELink supportPlatform:@[
                                                                          @(JSHAREPlatformWechatSession),
                                                                          @(JSHAREPlatformWechatTimeLine),
                                                                          @(JSHAREPlatformQQ),
                                                                          @(JSHAREPlatformQzone),
                                                                          ]];
    [view addSubview:shareTool.shareView];
    
}



/**
 分享视图
 
 @return 分享视图
 */
- (ShareView *)shareView{
    if (!_shareView) {
        _shareView = [ShareView getFactoryShareViewWithCallBack:^(JSHAREPlatform platform, JSHAREMediaType type) {
            
            [self shareLinkWithPlatform:platform];
            
        }];
    }
    return _shareView;
}


/**
 分享操作
 
 @param platform 分享平台信息
 */
- (void)shareLinkWithPlatform:(JSHAREPlatform)platform{
    self.shareMsg.platform = platform;
    //针对不平分享平台图片大小处理
    [self handleShareImage:self.shareMsg];
    [JSHAREService share:self.shareMsg handler:^(JSHAREState state, NSError *error) {
        [self showAlertWithState:state error:error];
    }];
    
}


/**
 分享回调
 
 @param state 状态值
 @param error 错误码
 */
- (void)showAlertWithState:(JSHAREState)state error:(NSError *)error{
    
    NSString *string = nil;
    if (state == JSHAREStateFail) {
        string = [NSString stringWithFormat:@"分享失败,error:%@", error.description];
    }else{
        switch (state) {
            case JSHAREStateSuccess:
                string = @"分享成功";
                break;
            case JSHAREStateFail:
                string = @"分享失败";
                break;
            case JSHAREStateCancel:
                string = @"分享取消";
                break;
            case JSHAREStateUnknown:
                string = @"Unknown";
                break;
            default:
                break;
        }
    }
    
    if ([string isEqualToString:@"Unknown"]) {
        return;
    }
    
    UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:nil message:string delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
        [Alert show];
    });
}


- (void)handleShareImage:(JSHAREMessage *)shareMsg{
    if (shareMsg.platform == JSHAREPlatformWechatSession || shareMsg.platform == JSHAREPlatformWechatTimeLine) {
        self.shareMsg.image = [self compressImage: self.shareMsg.image maxKB:10*1024];
        self.shareMsg.thumbnail = [self compressImage: self.shareMsg.thumbnail maxKB:32];

    }
    
    if (shareMsg.platform == JSHAREPlatformQQ || shareMsg.platform == JSHAREPlatformQzone) {
        self.shareMsg.image = [self compressImage: self.shareMsg.image maxKB:5*1024];
        self.shareMsg.thumbnail = [self compressImage: self.shareMsg.thumbnail maxKB:1*1024];
    }
    
}


// 图片压缩处理
- (NSData *)compressImage:(NSData *)imageData maxKB:(NSUInteger)maxKB{

    if (imageData && imageData.length <= 1024 * maxKB) {
        NSLog(@"无须压缩大小 = %ld KB", imageData.length / 1024);
        return imageData;
    }
    
    CGFloat compression = 1;
    CGFloat max = 1;
    CGFloat min = 0;
    
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        imageData = UIImageJPEGRepresentation([UIImage imageWithData:imageData], compression);
        //NSLog(@"Compression = %.1f", compression);
        //NSLog(@"In compressing quality loop, image size = %ld KB", data.length / 1024);
        if (imageData.length < 1024 * maxKB * 0.9) {
            min = compression;
        } else if (imageData.length > 1024 * maxKB) {
            max = compression;
        } else {
            break;
        }
    }
    
    if (imageData.length < 1024 * maxKB){
        NSLog(@"质量压缩后大小 = %ld KB", imageData.length / 1024);
        return imageData;
    }
    
    UIImage *resultImage = [UIImage imageWithData:imageData];
    NSUInteger lastDataLength = 0;
    while (imageData.length > 1024 * maxKB && imageData.length != lastDataLength) {
        lastDataLength = imageData.length;
        CGFloat ratio = (CGFloat)1024 * maxKB / imageData.length;
//        NSLog(@"尺寸压缩比例 = %.1f", ratio);
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        imageData = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    NSLog(@"质量尺寸压缩后大小 = %ld KB", imageData.length / 1024);
    return imageData;
}

@end
